import { computed, onBeforeMount, onMounted, reactive, ref } from 'vue';
import vueRouter from '@/router';

const message = window['$message'];
const dialog = window['$dialog'];

export interface ScrollPageParams<T> {
  // 当前页码
  pageNum: number;
  // 每页条数
  pageSize: number;
  // 总条数
  total: number;
  // 数据
  data: T[];
  // 是否加载中
  loading: boolean;
  // 是否加载完毕
  finished: boolean;
}
interface Option {
  params?: object;
  loadData?: Function;
}
export function useScrollPage<T>(option: Option = {}) {
  onBeforeMount(async () => {
    await getPageData();
  });
  const router = vueRouter;
  const route = vueRouter.currentRoute.value;
  const scrollPageRef = ref<any>({});
  const scrollPageState = reactive<ScrollPageParams<T>>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    data: [],
    loading: false,
    finished: false,
  });
  // naive-ui scrollbar滚动区域滚动事件
  async function scrollChange(e) {
    if (scrollPageState.loading || scrollPageState.finished) return;
    const { scrollTop, scrollHeight, clientHeight } = e.target;
    if (scrollTop + clientHeight >= scrollHeight) {
      await getPageData();
    }
  }
  // 获取分页数据
  async function getPageData() {
    try {
      if (option.loadData) {
        scrollPageState.loading = true;
        const res = await option.loadData({
          pageNum: scrollPageState.pageNum,
          pageSize: scrollPageState.pageSize,
        });
        scrollPageState.total = res.total;
        if (res.records.length > 0) {
          scrollPageState.pageNum++;
          scrollPageState.data = [...scrollPageState.data, ...res.records];
          if (scrollPageState.data.length >= scrollPageState.total) {
            scrollPageState.finished = true;
          }
        } else {
          scrollPageState.finished = true;
        }
      }
    } catch (err) {
      console.log(err);
    } finally {
      scrollPageState.loading = false;
    }
  }
  // 刷新数据
  async function refreshData() {
    scrollPageState.pageNum = 1;
    scrollPageState.data = [];
    scrollPageState.finished = false;
    await getPageData();
  }
  return {
    router,
    route,
    scrollPageRef,
    scrollPageState,
    refreshData,
    scrollChange,
  };
}
